﻿// =====================================================================
//
//  This file is part of the Microsoft Dynamics CRM SDK code samples.
//
//  Copyright (C) Microsoft Corporation.  All rights reserved.
//
//  This source code is intended only as a supplement to Microsoft
//  Development Tools and/or on-line documentation.  See these other
//  materials for detailed information regarding Microsoft code samples.
//
//  THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
//  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//  PARTICULAR PURPOSE.
//
// =====================================================================
#region

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

#endregion

namespace Microsoft.Xrm.Sdk.Client.Protocols.Policy
{
	internal sealed class XrmPolicyManager : IPolicyImporter
	{
		private readonly ServicePolicyImporterList _policyImporters = new ServicePolicyImporterList();


		public XrmPolicyManager()
		{
			InitializeDefaultImporters();
		}


		private ServicePolicyImporterList PolicyImporters
		{
			get { return _policyImporters; }
		}

		#region IPolicyImporter Members

		public bool CanImport(XDocument document)
		{
			return _policyImporters.Cast<IPolicyImporter>().Any(importer => importer.CanImport(document));
		}

		public ServicePolicy ImportPolicy(XDocument document)
		{
			return (from IPolicyImporter importer in _policyImporters
					where importer.CanImport(document)
					select importer.ImportPolicy(document)).FirstOrDefault();
		}

		#endregion

		public void InitializeDefaultImporters()
		{
			_policyImporters.Add(new AuthenticationPolicyImporter());
			_policyImporters.Add(new EndorsingSupportingTokenPolicyImporter());
			_policyImporters.Add(new SignedSupportingTokenPolicyImporter());
		}
	}

	public sealed class ServicePolicyImporterList : List<ServicePolicyImporter>
	{
	}

	public interface IPolicyImporter
	{
		Boolean CanImport(XDocument document);
		ServicePolicy ImportPolicy(XDocument document);
	}
}
